from flask import Flask, render_template, request, jsonify, session, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
import json
from datetime import datetime
from models import db, User, CalendarNote
from lunar_python import Lunar, Solar  # 添加农历库导入

app = Flask(__name__)
app.config.from_object('config.Config')

# 初始化扩展
db.init_app(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route('/')
@login_required
def index():
    return render_template('calendar.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        user = User.query.filter_by(username=username).first()
        
        if user and check_password_hash(user.password_hash, password):
            login_user(user)
            return redirect(url_for('index'))
        return '用户名或密码错误'
    
    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=username).first():
            flash('用户名已存在')
            return redirect(url_for('register'))
        
        # 创建新用户
        user = User(
            username=username,
            password_hash=generate_password_hash(password)
        )
        db.session.add(user)
        
        try:
            db.session.commit()
            flash('注册成功，请登录')
            return redirect(url_for('login'))
        except:
            db.session.rollback()
            flash('注册失败，请重试')
            return redirect(url_for('register'))
    
    return render_template('register.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

@app.route('/api/notes', methods=['GET'])
@login_required
def get_notes():
    notes = CalendarNote.query.filter_by(user_id=current_user.id).all()
    return jsonify({
        note.date: {
            'text': note.note_text,
            'bgColor': note.background_color
        } for note in notes
    })

@app.route('/api/notes', methods=['POST'])
@login_required
def save_note():
    data = request.json
    date = data.get('date')
    note_text = data.get('note', {}).get('text')
    bg_color = data.get('note', {}).get('bgColor')
    
    note = CalendarNote.query.filter_by(
        user_id=current_user.id,
        date=date
    ).first()
    
    if note:
        note.note_text = note_text
        note.background_color = bg_color
    else:
        note = CalendarNote(
            user_id=current_user.id,
            date=date,
            note_text=note_text,
            background_color=bg_color
        )
        db.session.add(note)
    
    db.session.commit()
    return jsonify({'status': 'success'})

@app.route('/api/notes', methods=['DELETE'])
@login_required
def delete_note():
    data = request.json
    date = data.get('date')
    
    try:
        note = CalendarNote.query.filter_by(
            user_id=current_user.id,
            date=date
        ).first()
        
        if note:
            db.session.delete(note)
            db.session.commit()
            
        return jsonify({'status': 'success'})
    except:
        db.session.rollback()
        return jsonify({'error': '删除失败'}), 500

@app.route('/api/lunar/<date>')
def get_lunar_date(date):
    try:
        # 解析日期字符串
        year, month, day = map(int, date.split('-'))
        
        # 创建阳历日期对象并转换为农历
        lunar = Lunar.fromYmd(year, month, day)
        
        # 获取农历信息
        lunar_month = lunar.getMonthInChinese()
        lunar_day = lunar.getDayInChinese()
        
        # 获取节气信息
        jieqi = lunar.getJieQi()  # 使用lunar对象获取节气
        
        # 组合农历日期字符串
        lunar_date = f"{lunar_month}月{lunar_day}"
        if jieqi:
            lunar_date = f"{lunar_date} ({jieqi})"
            
        return jsonify({'lunar_date': lunar_date})
    except Exception as e:
        print(f"农历转换错误: {str(e)}")  # 添加错误日志
        return jsonify({'lunar_date': '获取失败'}), 200  # 返回200而不是400，避免前端报错

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True) 